#!/usr/bin/env python
## Copyright (C) 2010, Scott W. Dunlop <swdunlop@gmail.com>
## All rights reserved.
## 
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##    * Redistributions of source code must retain the above copyright
##      notice, this list of conditions and the following disclaimer.
##    * Redistributions in binary form must reproduce the above copyright
##      notice, this list of conditions and the following disclaimer in the
##      documentation and/or other materials provided with the distribution.
##    * Neither the name of the <organization> nor the
##      names of its contributors may be used to endorse or promote products
##      derived from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
## ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
## DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
## LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
## ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 
## THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
This NoSpex demonstration reads hops from one or more LFT traces, and graphs them.  Nodes, here, are IPv4 addresses, strung with links.  This becomes interesting when plotting multiple chains from multiple traces.
"""

import threading, time, re, subprocess, os.path, sys
from cStringIO import StringIO
import nogo

def resolve_library_path( name ):
    if( os.path.exists( name ) ):
        return name

    for lib_dir in [ "/lib", "/usr/lib", "/usr/local/lib", "/opt/lib" ]:
        path = os.path.join( lib_dir, name )
        if os.path.exists( path ): return path

    return None

analyzed_libraries = set( )
# These libraries are so heavily used they will make ldv into a knot.
concealed_libraries = set((
    "libc.so", "libc.so.6",             # The standard C library.
    "libm.so", "libm.so.6",             # The standard Math library.
    "libpthread.so", "libpthread.so.0", # Pthreads.
    "linux-vdso.so.1",                  # More Linux glue.
    "ld-linux-x86-64.so.2",             # Ld, too..
    "libdl.so.2"
))

def analyze_library( name, path = None, depth = 0 ):
    print "+" + ("--" * depth) + name
    depth += 1
    # Barrier to uncontrolled recursion.
    if name in analyzed_libraries: return
    analyzed_libraries.add( name )
    
    if path is None:
        path = resolve_library_path( name )
        # Can't find it means can't analyze it.
        if path is None: 
            print "Could not resolve %s." % name
            return
    
    status, output = nogo.shell( "/usr/bin/ldd", path )
    if status: 
        print "LDD failed to understand %s." % path
        return
    origin = name

    for line in output.splitlines( ):
        line = line.split( )
        if len( line ) == 4:
            next = line[0]; path = line[2]
        else:
            next = line[0]
            if os.path.exists( next ):
                path = next 
                next = os.path.basename( next )
            else:
                path = None
        
        # Barrier to analysis of "anchor" libraries
        if next in concealed_libraries: continue 

        nogo.link( origin, next )
        analyze_library( next, path, depth )

def ldview( root ):
    analyze_library( root, root, 0 )

if __name__ == "__main__":
    if len( sys.argv ) < 2:
        ldview( "/usr/bin/vim.nox" )
    else:
        for name in sys.argv[1:]:
            ldview( name )


